package com.qiantu.phone.ui.activity;

import android.view.View;
import android.widget.LinearLayout;

import androidx.lifecycle.LifecycleOwner;
import androidx.recyclerview.widget.LinearLayoutManager;
import androidx.recyclerview.widget.RecyclerView;

import com.hjq.http.listener.HttpCallback;
import com.hjq.http.listener.OnHttpListener;
import com.hjq.permissions.XXPermissions;
import com.qiantu.api.db.LLDeviceCustomDBManager;
import com.qiantu.api.db.LLDeviceDBManager;
import com.qiantu.api.entity.DeviceCustomKeyBean;
import com.qiantu.api.entity.SwitchBindBean;
import com.qiantu.api.http.LLHttpManager;
import com.qiantu.api.http.model.HttpData;
import com.qiantu.phone.R;
import com.qiantu.phone.app.AppActivity;
import com.qiantu.phone.event.DeviceKeyChangeEvent;
import com.qiantu.phone.event.DeviceKeyNameChangeEvent;
import com.qiantu.phone.manager.ActivityManager;
import com.qiantu.phone.ui.adapter.PanelQRBingingAdapter;

import org.greenrobot.eventbus.EventBus;

import java.util.List;
import java.util.Map;

public class PanelQRBingingActivity extends AppActivity {
    public String coreId;
    private RecyclerView list;
    private PanelQRBingingAdapter adapter;
    private String panelSerialNo;
    private List<Map> bingingDatas;
    private int bingingCount = 0;
    private int checkCount = 0;
    private LinearLayout linearLayout;

    @Override
    protected int getLayoutId() {
        return R.layout.activity_panel_qrbinging;
    }

    @Override
    protected void initView() {
        linearLayout = findViewById(R.id.bottom_operate);
        list = findViewById(R.id.room_recycler_view);
        list.setLayoutManager(new LinearLayoutManager(getContext()));
        adapter = new PanelQRBingingAdapter(getContext());
        list.setAdapter(adapter);
        setOnClickListener(R.id.btn_retry,R.id.btn_finish);
    }

    @Override
    protected void initData() {
        bingingDatas = (List<Map>) getIntent().getSerializableExtra("bingingDatas");
        adapter.setData(bingingDatas);
        bingingData();
    }

    protected void bingingData(){
        Map bingingMap = bingingDatas.get(bingingCount);
        //请求接口
        LLHttpManager.addQuickBindSwitch(PanelQRBingingActivity.this, bingingMap, new HttpCallback<HttpData<Map>>(PanelQRBingingActivity.this) {
            @Override
            public void onSucceed(HttpData<Map> result) {
                super.onSucceed(result);
                if (result.getData() != null && result.getData().get("taskId") != null) {
                    //拿到CoreId后开始轮询等待服务器返回绑定成功 10秒后失败 3秒请求一次
                    coreId = result.getData().get("taskId").toString();
                    checkCount = 0;
                    postDelayed(pollingRunnable, 2000);//2秒后开始轮询
                    bingingDatas.get(bingingCount).put("bingingState",2);

                    adapter.notifyDataSetChanged();
                }else{
                    showFailView();
                }
            }

            @Override
            public void onFail(Exception e) {
                showFailView();
                super.onFail(e);
            }
        });
    }

    private final Runnable pollingRunnable = new Runnable() {
        @Override
        public void run() {
            requestInitQuery(coreId);
            postDelayed(pollingRunnable, 2000);//2秒后开始轮询
        }
    };

    public void requestInitQuery(String coreId) {
        LLHttpManager.queryQuickBindSwitch(PanelQRBingingActivity.this, coreId,bingingDatas.get(bingingCount).get("switchSerialNo").toString(),bingingDatas.get(bingingCount).get("switchKeyIndex").toString(), new HttpCallback<HttpData<SwitchBindBean>>(PanelQRBingingActivity.this) {
            @Override
            public void onSucceed(HttpData<SwitchBindBean> result) {
                super.onSucceed(result);
                if (result.getData() != null) {
                    int state = result.getData().getState();
                    switch (state) {
                        case 1://继续轮询等待
                            if(checkCount > 2){
                                showFailView();
                            }else{
                                checkCount++;
                            }
                            break;
                        case 2://绑定成功
                            removeCallbacks(pollingRunnable);
                            editKeyName();
                            break;
                        case 3://绑定失败
                        case 4://绑定超时
                            showFailView();
                            break;
                        case 5://绑定设备不存在
                            //showConfirmCancelHintDialog();
                            toast("设备不存在");
                            finish();
                        case 6://覆盖绑定成功
                            break;
                        case 7://存在绑定
                            break;
                    }
                }
            }

            @Override
            public void onFail(Exception e) {
                super.onFail(e);
            }
        });
    }

    protected void editKeyName(){
        Map map = bingingDatas.get(bingingCount);
        DeviceCustomKeyBean mEditKey = new DeviceCustomKeyBean();
        mEditKey.setDeviceSerialNo(map.get("switchSerialNo").toString());
        mEditKey.setCustomKeySerialNo("");
        mEditKey.setKeyIndex(map.get("switchKeyIndex").toString());
        LLHttpManager.saveCustomKeyName((LifecycleOwner) getContext(), mEditKey, map.get("info").toString(), new HttpCallback<HttpData<List<DeviceCustomKeyBean>>>(this){
            @Override
            public void onSucceed(HttpData<List<DeviceCustomKeyBean>> result) {
                super.onSucceed(result);
                List<DeviceCustomKeyBean> beans = result.getData();
                bingingDatas.get(bingingCount).put("bingingState",1);
                bingingCount++;
                for(DeviceCustomKeyBean bean : beans){
                    LLDeviceCustomDBManager.getInstance(getContext()).put(bean);
                }
                if(bingingCount >= bingingDatas.size()){
                    EventBus.getDefault().post(new DeviceKeyNameChangeEvent("",""));
                    //绑定结束
                    getAllEditData();;
                }else{
                    bingingData();
                }
            }
        });
    }

    @Override
    public void onClick(View view) {
        switch (view.getId()) {
            case R.id.btn_retry:
                linearLayout.setVisibility(View.GONE);
                bingingData();
                break;
            case R.id.btn_finish:
                ActivityManager.getInstance().finishActivity(PanelQRResultActivity.class);
                finish();
                break;
            default: {

            }
        }
    }

    protected void getAllEditData(){
        ActivityManager.getInstance().finishActivity(PanelQRResultActivity.class);
        ActivityManager.getInstance().finishActivity(PanelBingingActivity.class);
        finish();
    }

    protected void showFailView(){
        linearLayout.setVisibility(View.VISIBLE);
        bingingDatas.get(bingingCount).put("bingingState",0);
        adapter.notifyDataSetChanged();
    }

    @Override
    public void onRightClick(View view) {

    }
}
